import { Modal } from "antd";
import React, { useEffect, useState } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { LockState } from "@meta2d/core";
import beautify from "js-beautify";
import { vscodeDark } from "@uiw/codemirror-theme-vscode";
interface Props {
  open: boolean;
  onCancel: () => void;
  onOk: (codeText: string) => void;
  value: string;
  tip?: string;
}

export function ReactAceEditor(props: Props) {
  const [codeText, setCodeText] = useState<string>(props.value);
  useEffect(() => {
    let code = props.value;
    if (props.value != "") {
      code = beautify(code, {
        indent_size: 2, //缩进两个空格
        space_in_empty_paren: true,
      });
    }
    setCodeText(() => code);
  }, [props.value]);
  useEffect(() => {
    if (props.open) {
      window.meta2d.store.data.locked = LockState.Disable;
    }
  }, [props.open]);
  const onChange = React.useCallback((value: React.SetStateAction<string>) => {
    setCodeText(value);
  }, []);
  const handleOk = () => {
    window.meta2d.store.data.locked = LockState.None;
    props.onOk(codeText);
  };
  const close = () => {
    window.meta2d.store.data.locked = LockState.None;
    props.onCancel();
  };
  return (
    <>
      <Modal
        title="Javascript"
        open={props.open}
        width={820}
        okText={"确定"}
        cancelText={"取消"}
        onCancel={close}
        onOk={handleOk}
      >
        <CodeMirror
          value={codeText}
          height="400px"
          theme={vscodeDark}
          autoFocus
          style={{
            fontSize: 18,
          }}
          extensions={[javascript({ jsx: false })]}
          onChange={onChange}
        />
        {props.tip && (
          <p
            style={{ lineHeight: 2 }}
            dangerouslySetInnerHTML={{ __html: props.tip || "" }}
          ></p>
        )}
      </Modal>
    </>
  );
}
